/**
 * @param {number[][]} intervals
 * @return {number[][]}
 */
const merge = function(intervals) {
    intervals = intervals.sort((a, b) => a[0] - b[0]);
    const result = [];
    if ( intervals.length > 0 ) {
        result.push(intervals[0]);
        for (let i = 1; i < intervals.length; i++) {
            let last = result.pop();
            if ( same(last, intervals[i]) )
                result.push(mergeSpace(last, intervals[i]));
            else
                result.push(last, intervals[i]);
        }
    }
    return result;
};

/**
 * 判定两个数组 其两个区间是否是相连
 * @param a
 * @param b
 * @returns {boolean}
 */
function same(a, b) {
    return !(a[1] < b[0]);
}

/**
 * 合并两个区间 mergeSpace([1,3], [2,4])  => [1,4]
 * @param a
 * @param b
 * @returns {number[]}
 */
function mergeSpace(a, b) {
    return [Math.min(a[0], b[0]), Math.max(a[1], b[1])];
}

console.log(merge([[1,3], [2, 6], [8,9], [10, 12]]));